package com.libraries.helper;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import com.libraries.entities.FormInfo;

import android.os.Message;

/**
 * 网络请求对象 (封装了post和get请求)
 * 
 * @author FreemanLee
 * 
 */
public class HttpHelper {
	private static final String TAG = "HttpHelper";

	public static final int NETWORK_UNAVAILABLE = 0x0;
	public static final int EXECUTE_SUCCESS = 0x1;
	public static final int EXECUTE_FAILURE = -0x1;
	public static final int EXECUTE_RUNNING = 0x2;
	public static final int EXECUTE_INTERRUPT = -0x2;

	private static final int TIMEOUT_CONNECTION = 50000;
	private static final String BOUNDARY = "---------------------------7da2137580612"; // 数据分隔线

	private static BasePreferences preferences = new BasePreferences();
	private static String cookie;

	/**
	 * 提交POST请求
	 * 
	 * @param url
	 *            请求地址
	 * @param params
	 *            参数集合
	 * @return Message
	 */
	public static Message executePost(String url, Map<String, Object> params) {
		BufferedReader reader = null;
		try {
			HttpParams hParams = new BasicHttpParams();
			// hParams.setParameter("charset", HTTP.UTF_8);
			HttpConnectionParams.setConnectionTimeout(hParams, TIMEOUT_CONNECTION);
			HttpConnectionParams.setSoTimeout(hParams, TIMEOUT_CONNECTION);
			HttpClient client = new DefaultHttpClient(hParams);
			HttpPost request = new HttpPost();
			addCookie(request);// 添加cookies
			request.setURI(new URI(url));
			// UrlEncodedFormEntity formEntity = new
			// UrlEncodedFormEntity(getNameValuePair((Map<String, Object>)
			// params));
			String json = "{\"data\":" + GJsonHelper.toJson(params) + "}";
			Logger.log(TAG, "executePost req", url, json);
			StringEntity entity = new StringEntity(json, HTTP.UTF_8);
			entity.setContentType("application/json");
			request.setEntity(entity);

			HttpResponse response = client.execute(request);
			int statusCode = response.getStatusLine().getStatusCode();
			Logger.log(TAG, "executePost resp", statusCode);
			if (statusCode != HttpStatus.SC_OK) {
				return getMessage(EXECUTE_FAILURE, statusCode, 0, "链接服务器失败!");
			}
			saveCookie(response);// 保存cookies
			reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer strBuffer = new StringBuffer("");
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuffer.append(line);
			}
			String respone = strBuffer.toString();
			Logger.log(TAG, "executePost resp111", respone);
			strBuffer.setLength(0);
			return getMessage(EXECUTE_SUCCESS, 0, 0, respone);
		} catch (Exception e) {
			e.printStackTrace();
			return getMessage(EXECUTE_FAILURE, 0, 0, "获取数据异常!");
		} finally {
			if (reader != null) {
				try {
					reader.close();
					reader = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 提交POST请求
	 * 
	 * @param url
	 *            请求地址
	 * @param params
	 *            参数集合
	 * @return Message
	 */
	public static Message executePost(String url, String params) {
		BufferedReader reader = null;
		try {
			HttpParams hParams = new BasicHttpParams();
			// hParams.setParameter("charset", HTTP.UTF_8);
			HttpConnectionParams.setConnectionTimeout(hParams, TIMEOUT_CONNECTION);
			HttpConnectionParams.setSoTimeout(hParams, TIMEOUT_CONNECTION);
			HttpClient client = new DefaultHttpClient(hParams);
			HttpPost request = new HttpPost();
			addCookie(request);// 添加cookies
			// request.setURI(new URI(url));
			// UrlEncodedFormEntity formEntity = new
			// UrlEncodedFormEntity(getNameValuePair((Map<String, Object>)
			// params));
			// StringEntity entity=new StringEntity(params, HTTP.UTF_8);
			// entity.setContentType("application/json");
			// request.setEntity(entity);
			url += params;
			Logger.log(TAG, "executePost req", url, params);
			request.setURI(new URI(url));
			HttpResponse response = client.execute(request);
			int statusCode = response.getStatusLine().getStatusCode();
			Logger.log(TAG, "executePost resp", statusCode);
			if (statusCode != HttpStatus.SC_OK) {
				return getMessage(EXECUTE_FAILURE, statusCode, 0, "链接服务器失败!");
			}
			saveCookie(response);// 保存cookies
			reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer strBuffer = new StringBuffer("");
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuffer.append(line);
			}
			String respone = strBuffer.toString();
			Logger.log(TAG, "executePost resp111", respone);
			strBuffer.setLength(0);
			return getMessage(EXECUTE_SUCCESS, 0, 0, respone);
		} catch (Exception e) {
			e.printStackTrace();
			return getMessage(EXECUTE_FAILURE, 0, 0, "获取数据异常!");
		} finally {
			if (reader != null) {
				try {
					reader.close();
					reader = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 提交POST请求
	 * 
	 * @param url
	 * @param params
	 * @param clazz
	 * @return
	 */
	public static Message executePost(String url, Map<String, Object> params, Class<?> clazz) {
		BufferedReader reader = null;
		try {
			HttpParams p = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(p, TIMEOUT_CONNECTION);
			HttpConnectionParams.setSoTimeout(p, TIMEOUT_CONNECTION);
			HttpClient client = new DefaultHttpClient(p);
			HttpPost request = new HttpPost();
			addCookie(request);// 添加cookie
			request.setURI(new URI(url));
			// UrlEncodedFormEntity formEntity = new
			// UrlEncodedFormEntity(getNameValuePair((Map<String, Object>)
			// params));
			String json = "{\"data\":" + GJsonHelper.toJson(params) + "}";
			StringEntity stringEntity = new StringEntity(json);
			stringEntity.setContentEncoding("UTF-8");
			stringEntity.setContentType("application/json");
			request.setEntity(stringEntity);

			HttpResponse response = client.execute(request);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				return getMessage(EXECUTE_FAILURE, statusCode, 0, "链接服务器失败!");
			}
			saveCookie(response);// 保存cookie
			reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer strBuffer = new StringBuffer("");
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuffer.append(line);
			}
			Logger.log(TAG, "executePost", strBuffer.toString());
			return getMsgByClass(clazz, EXECUTE_SUCCESS, 0, 0, strBuffer.toString());
		} catch (Exception e) {
			e.printStackTrace();
			return getMessage(EXECUTE_FAILURE, 0, 0, "获取数据异常!");
		} finally {
			if (reader != null) {
				try {
					reader.close();
					reader = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 提交GET请求
	 * 
	 * @param url
	 *            请求地址
	 * @param params
	 *            参数集合
	 * @param clazz
	 *            需要转换的类型
	 * @return Message
	 */
	public static Message executeGet(String url, Map<String, Object> params, Class<?> clazz) {
		BufferedReader reader = null;
		try {
			HttpParams httpParameters = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_CONNECTION);
			HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_CONNECTION);
			HttpClient client = new DefaultHttpClient(httpParameters);
			url = url + "?" + URLEncodedUtils.format(getNameValuePair(params), "utf-8");
			URI uri = new URI(url);
			Logger.log(TAG, "executeGet", url);
			HttpGet request = new HttpGet(uri);
			HttpResponse response = client.execute(request);
			int code = response.getStatusLine().getStatusCode();
			if (code != 200) {
				return getMessage(EXECUTE_FAILURE, 0, 0, "链接服务器失败!");
			}
			reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer strBuffer = new StringBuffer("");
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuffer.append(line);
			}
			Logger.log(TAG, "executeGet success", strBuffer);
			return getMsgByClass(clazz, EXECUTE_SUCCESS, 0, 0, strBuffer.toString());
		} catch (Exception e) {
			Logger.log(TAG, "executeGet Exception", e);
			e.printStackTrace();
			return getMessage(EXECUTE_FAILURE, 0, 0, "获取数据异常!");
		} finally {
			if (reader != null) {
				try {
					reader.close();
					reader = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 提交GET请求
	 * 
	 * @param url
	 *            请求地址
	 * @param params
	 *            参数集合
	 * @return Message
	 */
	public static Message executeGet(String url, Map<String, Object> params) {
		BufferedReader reader = null;
		try {
			HttpParams p = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(p, TIMEOUT_CONNECTION);
			HttpConnectionParams.setSoTimeout(p, TIMEOUT_CONNECTION);
			HttpClient client = new DefaultHttpClient(p);
			url = url + "?" + URLEncodedUtils.format(getNameValuePair(params), "utf-8");
			URI uri = new URI(url);
			Logger.log(TAG, "executeGet", url);
			HttpGet request = new HttpGet(uri);
			HttpResponse response = client.execute(request);
			int code = response.getStatusLine().getStatusCode();
			if (code != 200) {
				return getMessage(EXECUTE_FAILURE, 0, 0, "链接服务器失败!");
			}
			reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer strBuffer = new StringBuffer("");
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuffer.append(line);
			}
			return getMessage(EXECUTE_SUCCESS, 0, 0, strBuffer.toString());
		} catch (IOException e) {
			Logger.log(TAG, "executeGet IOException", e);
			return getMessage(EXECUTE_FAILURE, 0, 0, "获取数据异常!");
		} catch (URISyntaxException e) {
			Logger.log(TAG, "executeGet URISyntaxException", e);
			return getMessage(EXECUTE_FAILURE, 0, 0, "获取数据异常!");
		} catch (Exception e) {
			Logger.log(TAG, "executeGet Exception", e);
			return getMessage(EXECUTE_FAILURE, 0, 0, "获取数据异常!");
		} finally {
			if (reader != null) {
				try {
					reader.close();
					reader = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	// #############################################################################################################
	// ########################################## 上传文件请求
	// ####################################################
	// #############################################################################################################

	/**
	 * 一次上传多个文件
	 * 
	 * @param surl
	 * @param mParams
	 * @param formInfos
	 */
	public static Message postFiles(String surl, Map<String, Object> mParams, FormInfo[] formInfos) throws Exception {
		final String endline = "--" + BOUNDARY + "--\r\n";// 数据结束标志
		int fileDataLength = 0;
		for (FormInfo formInfo : formInfos) {// 得到文件类型数据的总长度
			StringBuilder fileExplain = new StringBuilder();
			fileExplain.append("--");
			fileExplain.append(BOUNDARY);
			fileExplain.append("\r\n");
			fileExplain.append("Content-Disposition: form-data;name=\"" + formInfo.getParamName() + "\";filename=\""
					+ formInfo.getFileName() + "\"\r\n");
			fileExplain.append("Content-Type: " + formInfo.getContentType() + "\r\n\r\n");
			fileExplain.append("\r\n");
			fileDataLength += fileExplain.length();
			if (formInfo.getInStream() != null) {
				fileDataLength += formInfo.getFile().length();
			} else {
				fileDataLength += formInfo.getData().length;
			}
		}
		StringBuilder textEntity = new StringBuilder();
		for (Map.Entry<String, Object> entry : mParams.entrySet()) {// 构造文本类型参数的实体数据
			textEntity.append("--");
			textEntity.append(BOUNDARY);
			textEntity.append("\r\n");
			textEntity.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
			textEntity.append(entry.getValue());
			textEntity.append("\r\n");
		}
		// 计算传输给服务器的实体数据总长度
		int dataLength = textEntity.toString().getBytes().length + fileDataLength + endline.getBytes().length;

		URL url = new URL(surl);
		int port = url.getPort() == -1 ? 80 : url.getPort();
		Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);
		OutputStream outStream = socket.getOutputStream();
		// 下面完成HTTP请求头的发送
		String requestmethod = "POST " + url.getPath() + " HTTP/1.1\r\n";
		outStream.write(requestmethod.getBytes());
		String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash,"
				+ " application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, "
				+ "application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";
		outStream.write(accept.getBytes());
		String language = "Accept-Language: zh-CN\r\n";
		outStream.write(language.getBytes());
		String contenttype = "Content-Type: multipart/form-data; boundary=" + BOUNDARY + "\r\n";
		outStream.write(contenttype.getBytes());
		String contentlength = "Content-Length: " + dataLength + "\r\n";
		outStream.write(contentlength.getBytes());
		String alive = "Connection: Keep-Alive\r\n";
		outStream.write(alive.getBytes());
		String host = "Host: " + url.getHost() + ":" + port + "\r\n";
		outStream.write(host.getBytes());
		// 写完HTTP请求头后根据HTTP协议再写一个回车换行
		outStream.write("\r\n".getBytes());
		// 把所有文本类型的实体数据发送出来
		outStream.write(textEntity.toString().getBytes());
		// 把所有文件类型的实体数据发送出来
		for (FormInfo formInfo : formInfos) {
			StringBuilder fileEntity = new StringBuilder();
			fileEntity.append("--");
			fileEntity.append(BOUNDARY);
			fileEntity.append("\r\n");
			fileEntity.append("Content-Disposition: form-data;name=\"" + formInfo.getParamName() + "\";filename=\""
					+ formInfo.getFileName() + "\"\r\n");
			fileEntity.append("Content-Type: " + formInfo.getContentType() + "\r\n\r\n");
			outStream.write(fileEntity.toString().getBytes());
			if (formInfo.getInStream() != null) {
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = formInfo.getInStream().read(buffer, 0, 1024)) != -1) {
					outStream.write(buffer, 0, len);
				}
				formInfo.getInStream().close();
			} else {
				outStream.write(formInfo.getData(), 0, formInfo.getData().length);
			}
			outStream.write("\r\n".getBytes());
		}
		// 下面发送数据结束标志，表示数据已经结束
		outStream.write(endline.getBytes());

		BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		if (reader.readLine().indexOf("200") == -1) {// 读取web服务器返回的数据，判断请求码是否为200，如果不是200，代表请求失败
			outStream.flush();
			outStream.close();
			reader.close();
			socket.close();
			return getMessage(EXECUTE_FAILURE, 0, 0, "上传文件失败!");
		}
		outStream.flush();
		outStream.close();
		reader.close();
		socket.close();
		return getMessage(EXECUTE_SUCCESS);
	}

	/**
	 * 上传单个文件
	 * 
	 * @param surl
	 * @param mParams
	 * @param filePath
	 * @param fileName
	 * @return
	 */
	public static Message postFile(String surl, Map<String, Object> mParams, String filePath, String fileName) {
		HttpURLConnection conn = null;
		DataOutputStream outStream = null;
		try {
			String MULTIPART_FORM_DATA = "multipart/form-data";
			URL url = new URL(surl);
			// 参数上传
			StringBuilder sbParams = new StringBuilder();

			Set<String> keys = mParams.keySet();
			for (String key : keys) {
				sbParams.append("--");
				sbParams.append(BOUNDARY);
				sbParams.append("\r\n");
				sbParams.append("Content-Disposition:form-data;name=\"" + key + "\"\r\n\r\n");
				sbParams.append(mParams.get(key));
				sbParams.append("\r\n");
			}
			// 文件内容上传
			StringBuilder sbFile = new StringBuilder();
			sbFile.append("--");
			sbFile.append(BOUNDARY);
			sbFile.append("\r\n");
			sbFile.append("Content-Disposition:form-data;name=\"file\";filename=\"" + fileName + "\"\r\n");// a.jpg
			sbFile.append("Content-Type:image/png\r\n\r\n");

			byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();//

			File file = new File(filePath);
			FileInputStream fileIS = new FileInputStream(file);

			long contentLenght = sbParams.toString().getBytes().length + end_data.length
					+ sbFile.toString().getBytes().length + file.length() + "\r\n".getBytes().length;
			Logger.log(TAG, "postFile", url);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true); // 允许输入
			conn.setDoOutput(true); // 允许输出
			conn.setUseCaches(false); // 不使用caches
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + ";boundary=" + BOUNDARY);
			conn.setRequestProperty("Content-Length", Long.toString(contentLenght));

			outStream = new DataOutputStream(conn.getOutputStream());

			outStream.write(sbParams.toString().getBytes());

			outStream.write(sbFile.toString().getBytes());
			sbParams.setLength(0);
			sbParams = null;
			sbFile.setLength(0);
			sbFile = null;
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fileIS.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			outStream.write("\r\n".getBytes());

			outStream.write(end_data);
			outStream.flush();
			fileIS.close();
			int cah = conn.getResponseCode();
			if (cah != 200) {
				return getMessage(EXECUTE_FAILURE, 0, 0, "链接服务器失败!");
			}
			InputStream is = conn.getInputStream();
			int ch;
			StringBuilder result = new StringBuilder();
			while ((ch = is.read()) != -1) {
				result.append((char) ch);
			}
			return getMessage(EXECUTE_SUCCESS, 0, 0, result.toString());
		} catch (IOException e) {
			e.printStackTrace();
			return getMessage(EXECUTE_FAILURE, 0, 0, "上传失败!");
		} finally {
			try {
				if (outStream != null) {
					outStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
	}

	/**
	 * 上传单个文件
	 * 
	 * @param surl
	 * @param mParams
	 * @param fileBytes
	 * @param filename
	 * @return
	 */
	public static Message postFile(String surl, Map<String, Object> mParams, byte[] fileBytes, String filename) {
		HttpURLConnection conn = null;
		DataOutputStream outStream = null;
		try {
			String MULTIPART_FORM_DATA = "multipart/form-data";
			URL url = new URL(surl);
			// 参数上传
			StringBuilder sbParams = new StringBuilder();

			Set<String> keys = mParams.keySet();
			for (String key : keys) {
				sbParams.append("--");
				sbParams.append(BOUNDARY);
				sbParams.append("\r\n");
				sbParams.append("Content-Disposition:form-data;name=\"" + key + "\"\r\n\r\n");
				sbParams.append(mParams.get(key));
				sbParams.append("\r\n");
			}
			// 文件内容上传
			StringBuilder sbFile = new StringBuilder();
			sbFile.append("--");
			sbFile.append(BOUNDARY);
			sbFile.append("\r\n");
			sbFile.append("Content-Disposition:form-data;name=\"file\";filename=\"" + filename + "\"\r\n");// a.jpg
			sbFile.append("Content-Type:image/png\r\n\r\n");

			byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();//

			ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes);
			long contentLenght = sbParams.toString().getBytes().length + end_data.length
					+ sbFile.toString().getBytes().length + fileBytes.length + "\r\n".getBytes().length;
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true); // 允许输入
			conn.setDoOutput(true); // 允许输出
			conn.setUseCaches(false); // 不使用caches
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + ";boundary=" + BOUNDARY);
			conn.setRequestProperty("Content-Length", Long.toString(contentLenght));

			outStream = new DataOutputStream(conn.getOutputStream());

			outStream.write(sbParams.toString().getBytes());

			outStream.write(sbFile.toString().getBytes());
			sbParams.setLength(0);
			sbParams = null;
			sbFile.setLength(0);
			sbFile = null;
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inputStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			outStream.write("\r\n".getBytes());

			outStream.write(end_data);
			outStream.flush();
			inputStream.close();
			int cah = conn.getResponseCode();
			if (cah != 200) {
				return getMessage(EXECUTE_FAILURE, 0, 0, "上传失败!");
			}
			InputStream is = conn.getInputStream();
			int ch;
			StringBuilder result = new StringBuilder();
			while ((ch = is.read()) != -1) {
				result.append((char) ch);
			}
			return getMessage(EXECUTE_SUCCESS, 0, 0, result.toString());
		} catch (IOException e) {
			e.printStackTrace();
			return getMessage(EXECUTE_FAILURE, 0, 0, "上传失败!");
		} finally {
			try {
				if (outStream != null) {
					outStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
	}

	/**
	 * 转换Map<String,Object> 为 List<NameValuePair>
	 * 
	 * @param mParams
	 * @return
	 */
	private static List<NameValuePair> getNameValuePair(Map<String, Object> mParams) {
		List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
		for (Map.Entry<String, Object> entry : mParams.entrySet()) {// 构造文本类型参数的实体数据
			Object value = entry.getValue();
			String key = entry.getKey();
			if (value instanceof List) {
				@SuppressWarnings("rawtypes")
				List list = (List) value;
				int size = list.size();
				for (int vari = 0; vari < size; vari++) {
					valuePairs.add(new BasicNameValuePair(key, list.get(vari).toString()));
				}
			} else if (value instanceof String[]) {
				String[] values = (String[]) value;
				for (String value1 : values) {
					valuePairs.add(new BasicNameValuePair(key, value1));
				}
			} else if (value instanceof Object[]) {
				Object[] objs = (Object[]) value;
				for (Object obj : objs) {
					valuePairs.add(new BasicNameValuePair(key, obj + ""));
				}
			} else {
				valuePairs.add(new BasicNameValuePair(key, entry.getValue() + ""));
			}
		}
		return valuePairs;
	}

	private static void saveCookie(HttpResponse httpResponse) {
		org.apache.http.Header[] headers = httpResponse.getHeaders("Set-Cookie");
		Logger.log(TAG, "saveCookie", headers.toString());
		if (headers == null)
			return;
		for (int i = 0; i < headers.length; i++) {
			String cookieValue = headers[i].getValue();
			String[] cookieValues = cookieValue.split(";");
			for (String keyPair : cookieValues) {
				String[] keyPairs = keyPair.split("=");
				String key = keyPairs[0].trim();
				String value = keyPairs.length > 1 ? keyPairs[1].trim() : "";
				if (key.equals("JSESSIONID")) {
					cookie = key + "=" + value;
					preferences.setPreferences("cookie", cookie);
					break;
				}
			}
		}
	}

	/**
	 * 增加Cookie
	 * 
	 * @param request
	 */
	private static void addCookie(HttpPost request) {
		Logger.log(TAG, "addCookie", cookie);
		if (!StringHelper.hasValue(cookie)) {
			cookie = preferences.getString("cookie");
		}
		Logger.log(TAG, "addCookie~~~", cookie);
		if (!StringHelper.hasValue(cookie)) {
			return;
		}
		request.addHeader("cookie", cookie);
	}

	public static Message getMessage(Object... objs) {
		Message msg = Message.obtain();
		switch (objs.length) {
		case 1:
			msg.what = (int) objs[0];
			break;
		case 2:
			msg.what = (int) objs[0];
			msg.arg1 = (int) objs[1];
			break;
		case 3:
			msg.what = (int) objs[0];
			msg.arg1 = (int) objs[1];
			msg.arg2 = (int) objs[2];
			break;
		case 4:
			msg.what = (int) objs[0];
			msg.arg1 = (int) objs[1];
			msg.arg2 = (int) objs[2];
			msg.obj = objs[3];
			break;
		default:
			break;
		}
		return msg;
	}

	public static Message getMsgByClass(Class<?> cls, Object... objs) {
		// Logger.log(TAG, "getMsgByClass",objs);
		Message msg = Message.obtain();
		switch (objs.length) {
		case 1:
			msg.what = (int) objs[0];
			break;
		case 2:
			msg.what = (int) objs[0];
			msg.arg1 = (int) objs[1];
			break;
		case 3:
			msg.what = (int) objs[0];
			msg.arg1 = (int) objs[1];
			msg.arg2 = (int) objs[2];
			break;
		case 4:
			msg.what = (int) objs[0];
			msg.arg1 = (int) objs[1];
			msg.arg2 = (int) objs[2];
			Object obj = GJsonHelper.fromJson(objs[3].toString(), cls);
			msg.obj = obj;
			break;
		default:
			break;
		}
		return msg;
	}
}
